package com.hc.accountservice.web;

import com.hc.accountservice.service.AccountService;
import com.hc.entity.PayRecord;
import com.hc.entity.Wallet;
import com.hc.utils.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @BelongsProject: hc
 * @BelongsPackage: com.hc.accountservice.web
 * @Author: WY
 * @CreateTime: 2022-10-19  19:54
 * @Descriprion: TODO
 * @Version: 1.0
 **/
@CrossOrigin
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    //查看支付记录(使用redis)
    @PostMapping("/check")
    public ResponseEntity check(@RequestBody PayRecord payRecord){
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        Long size = ops.size(payRecord.getUserId().toString()+"支付");
        if(size==0){
            List<PayRecord> payRecords = accountService.findByPage(payRecord);
            for (PayRecord record : payRecords) {
                ops.rightPush(payRecord.getUserId().toString()+"支付",record);
            }
            return new ResponseEntity("200","ok",payRecords);
        }else {
            List<Object> payRecords = ops.range(payRecord.getUserId().toString()+"支付", 0, -1);
            return new ResponseEntity("200","ok",payRecords);
        }
    }

    //查看余额
    @PostMapping("/balance")
    public ResponseEntity balance(@RequestBody Wallet wallet){
        wallet = accountService.findBalance(wallet.getUserId());
        return new ResponseEntity("200","OK",wallet);
    }

    //钱包充值
    @PostMapping("topup")
    public ResponseEntity topup(@RequestBody Wallet wallet){
        accountService.topUp(wallet);
        return ResponseEntity.SUCCESS;
    }

    //订单退款
    @PostMapping("/refund")
    public ResponseEntity refund(@RequestBody PayRecord payRecord){
        accountService.orderRefund(payRecord);
        return ResponseEntity.SUCCESS;
    }
}
